package instancecreate

import (
	"errors"
	"fmt"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/setting"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
	"log"
)

type DbCreateParam struct {
	ServiceName    string
	ServiceNetwork string
	DockerLabel          string
	OutPort        string
	Password       string
	UserName       string
}

type RedisCreateParam struct {
	ServiceName    string
	ServiceNetwork string
	OutPort        string
	DockerLabel          string
}

func CreateDb(dP DbCreateParam) error {
	var dS string
	if dP.DockerLabel == "" {
		dS = fmt.Sprintf(
			"sudo docker service create --name %s --network %s "+
				"-p %s:5432 --env POSTGRES_PASSWORD=%s --env POSTGRES_USER=%s %s/%s",
			dP.ServiceName,
			dP.ServiceNetwork,
			dP.OutPort,
			dP.Password,
			dP.UserName,
			setting.DockerRepo,
			setting.DockerPostgresImage,
		)
	} else {
		dS = fmt.Sprintf(
			"sudo docker service create --name %s --network %s "+
				"-p %s:5432 --env POSTGRES_PASSWORD=%s --env POSTGRES_USER=%s --constraint node.labels.kname==%s %s/%s" ,
			dP.ServiceName,
			dP.ServiceNetwork,
			dP.OutPort,
			dP.Password,
			dP.UserName,
			dP.DockerLabel,
			setting.DockerRepo,
			setting.DockerPostgresImage,
		)
	}

	sshClient, err := util.NewSshClient(setting.DockerManagerHost, setting.DockerManagerPort,
		setting.DockerManagerUser, setting.DockerManagerAuthKey)
	if err != nil {
		log.Println(err.Error())
		return err
	}

	errMsg, err := util.RunSshCommand(sshClient, dS)
	if err != nil {
		log.Println(err.Error())
		return errors.New(errMsg)
	}

	return nil
}

func CreateRedis(rP RedisCreateParam) error {
	var rS string
	if rP.DockerLabel == "" {
		rS = fmt.Sprintf(
			"sudo docker service create --name %s --network %s " +
				"-p %s:6379 %s/%s",
			rP.ServiceName,
			rP.ServiceNetwork,
			rP.OutPort,
			setting.DockerRepo,
			setting.DockerRedisImage,
		)
	} else {
		rS = fmt.Sprintf(
			"sudo docker service create --name %s --network %s " +
				"-p %s:6379 --constraint node.labels.kname==%s %s/%s",
			rP.ServiceName,
			rP.ServiceNetwork,
			rP.OutPort,
			rP.DockerLabel,
			setting.DockerRepo,
			setting.DockerRedisImage,
		)

	}
	sshClient, err := util.NewSshClient(setting.DockerManagerHost, setting.DockerManagerPort,
		setting.DockerManagerUser, setting.DockerManagerAuthKey)
	if err != nil {
		return err
	}

	errMsg, err := util.RunSshCommand(sshClient, rS)
	if err != nil{
		log.Println(err.Error(), errMsg)
		return errors.New(errMsg)
	}
	return nil
}


